<?php
/**
 * Created by JetBrains PhpStorm.
 * User: MeRo
 * Date: 15.09.13
 * Time: 14:53
 * To change this template use File | Settings | File Templates.
 */

require_once 'templates/train/lib.php';
class loadSurface extends renderElement
{
    public function __construct($contao) {
        $this->_contao = $contao;

        $this
            ->_initialRender()
            ->_render()
        ;
    }

    protected function _initialRender() {
        $this->_addElement('<div class="gridly">');

        $surfaces = $this->_getSurfaces();
        $firstSurfaceRow = true;
        $surfaceIndex = 0;

        foreach ($surfaces as $surface) {
            if ($surfaceIndex++ % 4 == 0) {
                $rowEnding = '</div>';
                if ($firstSurfaceRow === true) {
                    $rowEnding = '';
                    $firstSurfaceRow = false;
                }

                $this->_addElement($rowEnding . '<div class="row">');
            }
            $this->_addElement('<div id="' . $surface['id'] . '" class="brick autoscroll surface pointer">' .
                $surface['surface_name'] . '<br /><br />' .
                $surface['surface_x_size'] . ' x ' . $surface['surface_y_size'] . ' Felder<br /><br />
                vom ' . date("d.m.Y", strtotime($surface['surface_create_date'])) .
                '<div class="data invisible">' . json_encode($surface) . '</div>
            </div>');
        }

        $this->_addElement('</div>');
        return $this;
    }

    protected function _getSurfaces() {
        $memberIsAdmin  = 0;
        $memberId       = NULL;
        if (FE_USER_LOGGED_IN) {
            $memberIsAdmin = in_array(2, $this->_contao->Member->groups) === true ? '1' : '0';
            $memberId = $this->_contao->Member->id;

        }

        $result = $this->_contao->Database->prepare("
            SELECT
                s.*
            FROM    tr_surface s
            WHERE
                s.surface_public       = 1 OR
                s.surface_create_user  = ? OR
                ?
        ")->execute($memberId, $memberIsAdmin);

        return $result->fetchAllAssoc();
    }
}

$this->import('Database');
$this->import('FrontendUser', 'Member');
new loadSurface($this);
